import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'Index',
            component: () => import('@/views/Index/index.vue'),
            meta: { requiresAuth: false },
        },
        {
            path: '/index',
            name: 'Index',
            component: () => import('@/views/Index/index.vue'),
            meta: { requiresAuth: false },
        },
        {
            path: '/login',
            name: 'Login',
            component: () => import('@/views/Login/index.vue'),
            meta: { requiresGuest: true },
        },
        {
            path: '/register',
            name: 'Register',
            component: () => import('@/views/Register/index.vue'),
            meta: { requiresGuest: true },
        },
    ],
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()

    // 初始化用户状态
    if (!userStore.user && localStorage.getItem('leancloud_session_token')) {
        await userStore.init()
    }

    // 检查是否需要登录
    if (to.meta.requiresAuth && !userStore.isLoggedIn) {
        next('/login')
        return
    }

    // 检查是否需要未登录状态（已登录用户访问登录/注册页）
    if (to.meta.requiresGuest && userStore.isLoggedIn) {
        next('/')
        return
    }

    next()
})

export default router
